<?php

namespace app\api\controller;

use app\admin\model\factor\AccountAuthentication;
use app\admin\model\factor\Authority;
use app\admin\model\factor\CarbonFactor as CarbonFactorModel;
use app\admin\model\factor\CertificationBody;
use app\admin\model\factor\FactorReview;
use app\common\controller\Api;
use Qiniu\Auth;
use Qiniu\Http\Error;
use Qiniu\Storage\UploadManager;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\ValidateException;

/**
 * 碳排放因子库
 */
class CarbonFactor extends Api
{
    // 验证失败是否抛出异常
    protected $failException = true;
    protected $noNeedLogin = [];
    protected $noNeedRight = ["*"];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @title 我的碳数据库列表
     * @author Trace
     * @method GET
     * @url api/carbon_factor/myFactorList
     * @param xx 必选 string 用户名
     * @return_param error_code int 返回码
     * @DATE: 2024/7/24
     * @TIME: 下午5:08
     */
    public function myFactorList()
    {
        try {
            $user_id = $this->auth->id;
            $user = \app\admin\model\User::get($user_id);
            $factorCollectionIds = $user->factorCollection()->column('factor_id');
            $limit = $this->request->get('limit', 15);
            $search = $this->request->get('search', '');
            $type = $this->request->get('type', '');

            $list = CarbonFactorModel::join('zt_user', 'zt_user.id=zt_carbon_factor.user_id', 'left')
                ->where(function ($query) use ($factorCollectionIds, $user_id, $type) {
                    if ($type == 2) {
                        $query->where('zt_carbon_factor.id', 'in', $factorCollectionIds);
                    } else if ($type == 1) {
                        $query->where('zt_carbon_factor.user_id', $user_id);
                    } else {
                        $query->whereIn('zt_carbon_factor.id', $factorCollectionIds)->whereOr('zt_carbon_factor.user_id', $user_id);
                    }
//                    if ($factorCollectionIds) {
//                        $query->where('zt_carbon_factor.id', 'in', $factorCollectionIds)->whereOr('zt_carbon_factor.user_id', $user_id);
//                    } else {
//                        $query->where('zt_carbon_factor.user_id', $user_id);
//                    }
                })->where(function ($query) use ($search) {
                    if ($search) {
                        $query->where('zt_carbon_factor.name', 'like', '%' . $search . '%');
                    }
                })->field('zt_carbon_factor.id,zt_carbon_factor.sn,zt_carbon_factor.name,zt_carbon_factor.status,zt_carbon_factor.product_review,zt_carbon_factor.unit,zt_carbon_factor.lifecycle,zt_carbon_factor.is_account,zt_carbon_factor.is_authority,zt_carbon_factor.carbon_result,zt_carbon_factor.carbon_factor_result,zt_carbon_factor.carbon_factor_result_kg,zt_carbon_factor.user_id,zt_user.company_name')
                ->order('zt_carbon_factor.id', 'desc')
                ->paginate($limit)->each(function ($item) use ($factorCollectionIds) {
                    $item->is_collection = in_array($item->id, $factorCollectionIds) ? 1 : 0;
                    $last_factor_review = $item->getLastFactorReviewAttr();
                    $last_account_auth = $item->getLastAccountAuthAttr();
                    $last_authority_auth = $item->getLastAuthorityAuthAttr();
                    $item->product_review_status = 0;
                    $item->account_status = 0;
                    $item->authority_status = 0;
                    if ($item->product_review || ($item->is_account == 1 && $last_factor_review)) {
                        $item->product_review_status = 1;
                    }
                    if ($item->is_account || ($item->is_account == 0 && $last_account_auth)) {
                        $item->account_status = 1;
                    }
                    if ($item->is_authority || ($item->is_authority == 0 && $last_authority_auth)) {
                        $item->authority_status = 1;
                    }
                });

//            if ($search) {
//                if (!$user->searchHistory()->where('word', $search)->count()) {
//                    $user->searchHistory()->save(['word' => $search]);
//                }
//            }

            $this->success('请求成功', $list);
        } catch (DataNotFoundException|DbException|ModelNotFoundException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 碳数据库详情
     * @author Trace
     * @method GET
     * @url api/carbon_factor/factorDetail
     * @param factor_id 必选 string 数据库ID
     * @return_param error_code int 返回码
     * @DATE: 2024/7/24
     * @TIME: 下午5:08
     */
    public function factorDetail()
    {
        try {
            $factor_id = $this->request->get('factor_id');
            if (!$factor_id) {
                $this->error('参数错误');
            }
            $factor = CarbonFactorModel::alias('cf')
                ->join('zt_user u', 'u.id=cf.user_id', 'left')
                ->where('cf.id', $factor_id)
                ->field('cf.id,cf.down_type,cf.down_reason,cf.description,cf.images,cf.order_id,cf.sn,cf.name,cf.set_unit,cf.extra,cf.unit,cf.price,cf.lifecycle,cf.is_account,cf.is_authority,cf.carbon_result,cf.carbon_factor_result,cf.carbon_factor_result_kg,cf.product_review,cf.status,cf.user_id,cf.snapshot,cf.createtime,u.company_name')
                ->find()?->append(['createtime_text','last_account_auth','last_factor_review','last_authority_auth']);

            if ($factor) {
                $user_id = $this->auth->id;
                if ($factor->user_id != $user_id && $factor->status == 0) {
                     $this->error('数据库不存在');
                }
                $factor->product_info = [
                    'product_introduction' => $factor->description ?? '',
                    'product_image' => $factor->images ?? [],
                ];
                $factor->product_review_status = 0;
                $factor->account_status = 0;
                $factor->authority_status = 0;


                $user = \app\admin\model\User::get($user_id);
                $is_collection = (bool)$user->factorCollection()->where('factor_id', $factor->id)->count();
                $factor->is_collection = $is_collection ? 1 : 0;
                $factorReview = FactorReview::where('factor_id', $factor->id)->order('createtime', 'desc')->find();
                if ($factor->product_review || ($factor->is_account == 1 && $factorReview)) {
                    $factor->product_review_status = 1;
                }
                //核算认证状态
                $product_info = AccountAuthentication::where('factor_id', $factor->id)->find();
                if ($factor->is_account || ($factor->is_account == 0 && $product_info)) {
                    $factor->account_status = 1;
                }
//                product_name,product_introduction,product_image
//                if ($factor->is_account == 1) {
//                    $factor->product_info = [
//                        'product_introduction' => $factor->description ?? '',
//                        'product_image' => $factor->images ?? [],
//                    ];
//                }

                $authority_info = Authority::where('factor_id', $factor->id)->order('createtime', 'desc')->find();
                if ($factor->is_authority || ($factor->is_authority == 0 && $authority_info)) {
                    $factor->authority_status = 1;
                }

                if ($factor->extra) {
                    //总比例 carbon_result
                    $extra = $factor->extra;

                    $extra['ycl_kg_rate'] = $factor->carbon_factor_result_kg ? bcdiv($extra['ycl_kg'], $factor->carbon_factor_result_kg, 4) * 100 : 0;
                    $extra['cp_kg_rate'] = floatval(bcsub(100, $extra['ycl_kg_rate'], 4));
                    $extra['ycl_rate'] = $factor->carbon_factor_result ? bcdiv($extra['ycl'], $factor->carbon_factor_result, 4) * 100 : 0;
                    $extra['cp_rate'] = floatval(bcsub(100, $extra['ycl_rate'], 4));
                    $factor->extra = json_encode($extra, JSON_UNESCAPED_UNICODE);
                }
//                if (is_null()) $factor->company_name = '平台';
//                $factor->company_name = $factor->company_name ?: '平台';
//                $factor->append(['createtime_text']);

                $is_carbon = 0;
                if ($factor->order_id) {
                    $order = \app\admin\model\template\Order::where('id', $factor->order_id)->find();
                    if ($order) {
                        if (!empty($order->factors)) {
                            $is_carbon = 1;
                        }
                    }
                }
                $factor->is_carbon = $is_carbon;

            }
            $this->success('请求成功', $factor);
        } catch (DataNotFoundException|DbException|ModelNotFoundException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 碳数据库核算认证报告
     * @author Trace
     * @method GET
     * @url api/carbon_factor/factorAccountAuthDetail
     * @param factor_id 必选 string 数据库ID
     * @return_param error_code int 返回码
     * @DATE: 2024/7/24
     * @TIME: 下午5:08
     */
    public function factorAccountAuthDetail()
    {
        try {
            $factor_id = $this->request->get('factor_id');
            $this->validate($this->request->get(), 'app\admin\validate\factor\AccountAuthentication.factorAccountAuthDetail');

            $factor = CarbonFactorModel::where('id', $factor_id)
                ->field('id,sn,name,unit,lifecycle,carbon_result,carbon_factor_result,snapshot,carbon_factor_result_kg,extra')
                ->find();

            $authInfo = $factor->getLastAccountAuthAttr();
            if ($authInfo) {
                $authInfo->factor_name = $factor->name;
                $authInfo->lifecycle_text = $factor->lifecycle_text;
                $authInfo->carbon_result = $factor->carbon_result;
                $authInfo->carbon_factor_result = $factor->carbon_factor_result;
                $authInfo->carbon_factor_result_kg = $factor->carbon_factor_result_kg;
                $authInfo->unit = $factor->unit;
                $authInfo->extra = [];
                if ($factor->extra) {
                    //总比例 carbon_result
                    $extra = $factor->extra;
                    $extra['ycl_kg_rate'] = $factor->carbon_factor_result_kg ? bcdiv($extra['ycl_kg'], $factor->carbon_factor_result_kg, 4) * 100 : 0;
                    $extra['cp_kg_rate'] = floatval(bcsub(100, $extra['ycl_kg_rate'], 4));
                    $extra['ycl_rate'] = $factor->carbon_factor_result ? bcdiv($extra['ycl'], $factor->carbon_factor_result, 4) * 100 : 0;
                    $extra['cp_rate'] = floatval(bcsub(100, $extra['ycl_rate'], 4));
                    $authInfo->extra = $extra;
                }
                $authInfo->append(['checktime_text']);
            }

            $this->success('请求成功', $authInfo ?: []);
        } catch (DataNotFoundException|DbException|ModelNotFoundException|ValidateException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 取消核算认证
     * @author Trace
     * @method POST
     * @url api/carbon_factor/cancelAccountAuth
     * @param factor_id 必选 string 数据库ID
     * @return_param error_code int 返回码
     * @DATE: 2024/7/24
     * @TIME: 下午5:08
     */
    public function cancelAccountAuth()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
            $this->validate($this->request->post(), 'app\admin\validate\factor\AccountAuthentication.cancelAccountAuth');

            $factor_id = $this->request->post('factor_id');
            Db::transaction(function () use ($factor_id) {
                AccountAuthentication::where('factor_id', $factor_id)->delete();
                CarbonFactorModel::where('id', $factor_id)->update(['is_account' => 0, 'account_time' => null]);
            });

            $this->success('请求成功');
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 上架碳排放数据库
     * @author Trace
     * @method POST
     * @url api/carbon_factor/reviewFactor
     * @param price 必选 int 价格
     * @param product_introduction 必选 string 产品描述
     * @param product_image 必选 array 产品图片
     * @param factor_id 必选 int 数据库ID
     * @param category_id 必选 int 数据库类型ID
     */
    public function reviewFactor()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
            $this->validate($this->request->post(), 'app\admin\validate\factor\AccountAuthentication.reviewFactor');

            $price = $this->request->post('price');

            if ($price < 10) {
                $this->error('价格不能小于10');
            }
            if (strlen($price) > 6) {
                $this->error('请填写6位及以内的整数');
            }
            $factor_id = $this->request->post('factor_id');
            $factor = CarbonFactorModel::where('id', $factor_id)->find();
            $images = $this->request->post('images/a') ?: [];
            if (count($images) > 9) {
                $this->error('最多上传9张图片');
            }
            $data = [
                'factor_id' => $factor_id,
                'category_id' => $this->request->post('category_id'),
                'price' => $price,
                'description' => $this->request->post('description'),
                'images' => $images,
                'status' => 0,
            ];
            DB::transaction(function () use ($data, $factor) {
                FactorReview::create($data);
                $factor->product_review = 0;
                $factor->review_time = null;
                $factor->save();
            });
            $this->success('提交成功');
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 获取上架审核信息
     * @author Trace
     * @method Get
     * @url api/carbon_factor/getFactorReviewInfo
     * @param factor_id 必选 int 数据库ID
     */
    public function getFactorReviewInfo()
    {
        try {
            $this->validate($this->request->get(), 'app\admin\validate\factor\AccountAuthentication.getFactorReview');
            $factor_id = $this->request->get('factor_id');
            $factorReview = FactorReview::where('factor_id', $factor_id)
                ->field('id,price,status,category_id,description,images,reason,checktime,createtime')
                ->order('createtime', 'desc')
                ->find()?->append(['category_name']);
            $this->success('请求成功', $factorReview);
        } catch (DataNotFoundException|ModelNotFoundException|DbException|ValidateException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 获取核算认证报告
     * @author Trace
     * @method Post
     * @url api/carbon_factor/getAccountPdf
     * @param factor_id 必选 int 数据库ID
     */
    public function getAccountPdf()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
            $this->validate($this->request->post(), 'app\admin\validate\factor\AccountAuthentication.getAccountPdf');
            $base64 = $this->request->post('file_base64');
            if (!$base64) {
                $this->error('文件格式错误');
            }
            $img_data = base64_decode($base64);
            // 解码base64编码的图片数据
            $filepath = "factor_auth_pdf/" . md5(date('YmdHis')) . '.pdf';
            $qiniu_config = get_addon_config('qiniu');

            $accessKey = $qiniu_config['accessKey'];
            $secretKey = $qiniu_config['secretKey'];
            $bucketName = $qiniu_config['bucket'];

            $auth = new Auth($accessKey, $secretKey);
            $token = $auth->uploadToken($bucketName);
            $uploadMgr = new UploadManager();

            [$ret, $err] = $uploadMgr->put($token, $filepath, $img_data);
            if ($err !== null) {
                if ($err instanceof Error) {
                    $this->error('生成PDF失败：' . $err->message());
                }
                $this->error('生成PDF失败：', [$err, $ret]);
            }
            $ret['path'] = cdnurl('/' . $ret['key']);
            $this->success('生成PDF成功', $ret);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

    }

    //设置功能单位
    public function setFactorUnit()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
            $this->validate($this->request->post(), 'app\admin\validate\factor\AccountAuthentication.setFactorUnit');

            $factor_id = $this->request->post('factor_id');
            $unit = $this->request->post('unit', '', 'trim') ?: '';
            if ($unit) {
                if (!in_array($unit, ['kg', 'KG', '个', '辆', '千克'])) {
                    $this->error('单位错误');
                }
            }

            $factor = CarbonFactorModel::where('id', $factor_id)->find();
            if (!$factor) {
                $this->error('数据不存在', $factor);
            }
            $factor->set_unit = 1;
            $factor->unit = $unit;
            $factor->save();
            $this->success('提交成功');
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

    }


    /**
     * @title 碳数据库核算认证
     * @author Trace
     * @method GET
     * @url api/carbon_factor/factorAccountAuth
     * @param factor_id 必选 string 数据库ID
     * @return_param error_code int 返回码
     * @DATE: 2024/7/24
     * @TIME: 下午5:08
     */
    public function factorAccountAuth()
    {
        if ($this->request->isPost()) {
            try {
                $this->validate($this->request->post(), 'app\admin\validate\factor\AccountAuthentication.factorAccountAuth');

                $factor_id = $this->request->post('factor_id/d');
                $data = [
                    'factor_id' => $factor_id,
                    'user_id' => $this->auth->id,
                    'status' => 0
                ];

                $factor = CarbonFactorModel::where('id', $factor_id)->find();
                Db::transaction(function () use ($factor, $data) {
                    if ($factor->is_account == 2) {
                        $factor->is_account = 0;
                        $factor->account_time = null;
                        $factor->save();
                    }
                    $factor->accountAuth()->save($data);
                });
                $this->success("提交成功");
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }
        }
        $this->error('请求错误');

    }


    /**
     * @title 取消权威认证
     * @author Trace
     * @method POST
     * @url api/carbon_factor/cancelAuthorityAuth
     * @param factor_id 必选 string 数据库ID
     * @return_param error_code int 返回码
     * @DATE: 2024/7/24
     * @TIME: 下午5:08
     */
    public function cancelAuthorityAuth()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
            $this->validate($this->request->post(), 'app\admin\validate\factor\Authority.cancelAuthorityAuth');

            $factor_id = $this->request->post('factor_id/d');
            $factor = CarbonFactorModel::where('id', $factor_id)->find();
            if ($factor->is_authority == 1) {
                $this->error('数据已权威认证，无法取消');
            }
            $factor->is_authority = 0;
            $factor->authority_time = null;
            Db::transaction(function () use ($factor) {
                $factor->delete();
                $factor->authorityAuth()->delete();
            });

            $this->success('请求成功');
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * @title 碳排放数据库权威认证
     * @author Trace
     * @method POST
     * @url api/carbon_factor/authorityFactor
     * @param factor_id 必选 string 数据库ID
     * @param product_name 必选 string 产品名称
     * @param product_specification 必选 string 产品规格型号
     * @param product_function 必选 string 产品功能
     * @param auth_date 必选 sring 时间范围
     * @param product_image 必选 array 产品图片(最多9张)
     * @param quantification_method 必选 int 量化方法1.ISO,2.碳足迹量化要求
     */
    public function authorityFactor()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
            $this->validate($this->request->post(), 'app\admin\validate\factor\Authority.authorityFactor');

            $product_image = $this->request->post('product_image/a');

            if ($product_image) {
                if (count($product_image) > 20) {
                    $this->error('图片数量不能超过20张');
                }
            }
            $auth_date_start = $this->request->post('auth_date_start/s');
            $auth_date_end = $this->request->post('auth_date_end/s');
            if (strtotime($auth_date_start) == strtotime($auth_date_end)) {
                $this->error('时间范围不能相同');
            }
            if (strtotime($auth_date_start) > strtotime($auth_date_end)) {
                $this->error('时间范围不正确');
            }
            $data = [
                'product_name' => $this->request->post('product_name'),
                'product_specification' => $this->request->post('product_specification'),
                'product_function' => $this->request->post('product_function'),
                'auth_date_start' => $this->request->post('auth_date_start'),
                'auth_date_end' => $this->request->post('auth_date_end'),
                'product_image' => $product_image ?: [],
                'quantification_method' => $this->request->post('quantification_method'),
                'user_id' => $this->auth->id,
            ];

            $factor = CarbonFactorModel::where('id', $this->request->post('factor_id/d'))->find();
            DB::transaction(function () use ($data, $factor) {
                if ($factor->is_authority == 2) {
                    $factor->is_authority = 0;
                    $factor->authority_time = null;
                    $factor->save();
                }

                $factor->authorityAuth()->save($data);
            });
            $this->success("提交成功");
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * @title 碳数据库权威认证报告
     * @author Trace
     * @method GET
     * @url api/carbon_factor/factorAuthorityAuthDetail
     * @param factor_id 必选 string 数据库ID
     * @return_param error_code int 返回码
     * @DATE: 2024/7/24
     * @TIME: 下午5:08
     */
    public function factorAuthorityAuthDetail()
    {
        try {
            $factor_id = $this->request->get('factor_id');
            $this->validate($this->request->get(), 'app\admin\validate\factor\Authority.factorAuthorityAuthDetail');

            $factor = CarbonFactorModel::where('id', $factor_id)
                ->field('id,sn,name,unit,lifecycle,carbon_result,carbon_factor_result,snapshot,carbon_factor_result_kg,extra')
                ->find();

            $authInfo = $factor->authorityAuth()
                ->field('id,product_name,product_specification,auth_date_start,auth_date_end, product_function,product_image,report_sn,certification_stamp,checktime,status,reason,quantification_method')
                ->order('createtime', 'desc')
                ->find()?->append(['quantification_method_text']);

            if ($authInfo) {
                $authInfo->factor_name = $factor->name;
                $authInfo->lifecycle_text = $factor->lifecycle_text;
                $authInfo->carbon_result = $factor->carbon_result;
                $authInfo->carbon_factor_result = $factor->carbon_factor_result;
                $authInfo->carbon_factor_result_kg = $factor->carbon_factor_result_kg;
                $authInfo->unit = $factor->unit;
                $authInfo->extra = [];
                if ($factor->extra) {
                    //总比例 carbon_result
                    $extra = $factor->extra;
                    $extra['ycl_kg_rate'] = $factor->carbon_factor_result_kg ? bcdiv($extra['ycl_kg'], $factor->carbon_factor_result_kg, 4) * 100 : 0;
                    $extra['cp_kg_rate'] = floatval(bcsub(100, $extra['ycl_kg_rate'], 4));
                    $extra['ycl_rate'] = $factor->carbon_factor_result ? bcdiv($extra['ycl'], $factor->carbon_factor_result, 4) * 100 : 0;
                    $extra['cp_rate'] = floatval(bcsub(100, $extra['ycl_rate'], 4));
                    $authInfo->extra = $extra;
                }
            }

            $this->success('请求成功', $authInfo ?: []);
        } catch (DataNotFoundException|DbException|ModelNotFoundException|ValidateException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 获取权威认证报告
     * @author Trace
     * @method Post
     * @url api/carbon_factor/getAuthorityPdf
     * @param factor_id 必选 int 数据库ID
     */
    public function getAuthorityPdf()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
//            $this->validate($this->request->post(), 'app\admin\validate\factor\AccountAuthentication.getAccountPdf');
//            $base64 = $this->request->post('file_base64');
//            if (!$base64) {
//                $this->error('文件格式错误');
//            }
//            $img_data = base64_decode($base64);
//            // 解码base64编码的图片数据
//            $filepath = "factor_auth_pdf/" . md5(date('YmdHis')) . '.pdf';
//            $qiniu_config = get_addon_config('qiniu');
//
//            $accessKey = $qiniu_config['accessKey'];
//            $secretKey = $qiniu_config['secretKey'];
//            $bucketName = $qiniu_config['bucket'];
//
//            $auth = new Auth($accessKey, $secretKey);
//            $token = $auth->uploadToken($bucketName);
//            $uploadMgr = new UploadManager();
//
//            [$ret, $err] = $uploadMgr->put($token, $filepath, $img_data);
//            if ($err !== null) {
//                if ($err instanceof Error) {
//                    $this->error('生成PDF失败：' . $err->message());
//                }
//                $this->error('生成PDF失败：', [$err, $ret]);
//            }
            $ret['path'] = 'https://battery001.zthj.net/uploads/20240912/Fn4CV0HktVdP4z8dnl2-zA1s7c6O.pdf';
            $this->success('生成PDF成功', $ret);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

    }

    /**
     * @title 机构列表
     * @author Trace
     * @method POST
     * @url http://xx.com/api/carbon_factor/getCertificationList
     * @param xx 必选 string 用户名
     * @return_param error_code int 返回码
     * @DATE: 2024/9/12
     * @TIME: 09:44
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCertificationList()
    {
        $bodyName = CertificationBody::where('status', 1)
            ->field('id,body_image,body_name')
            ->limit(3)
            ->select();
        $this->success('请求成功', $bodyName);
    }

    //获取权威认证审核状态
    public function getAuthorityStatus()
    {
        try {
            $factor_id = $this->request->get('factor_id');
            $factor = CarbonFactorModel::where('id', $factor_id)->find()?->append(['last_authority_auth']);
            if (!$factor) {
                $this->error('数据不存在');
            }

            if (!$factor->is_authority) {
                if (!$factor->last_authority_auth) {
                    $authority_status = 0;//未提交
                } else {
                    $authority_status = match ($factor->last_authority_auth->status) {
                        1 => 2,
                        2 => 3,
                        default => 1,
                    };

                }
            } else {
                $authority_status = match ($factor->is_authority) {
                    1 => 2,
                    2 => 3,
                    default => 1,
                };
            }
            $this->success('获取成功',['authority_status' =>$authority_status]);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

    }
}
